<template>
    <v-card class="mx-auto" style="height:94vh">

        <v-card>
            <div style="display:flex; align-items:center; padding:5px 0 5px 12px;">
                <h3 @click="loadMatrixData()" style="margin:0; padding:0; white-space:nowrap;">缺陷分类矩阵图</h3>
                <div style="margin-left:30px;">
                    <v-select
                            v-model="selectedProblemClass"
                            :items="problemClassList"
                            item-text="label"
                            item-value="value"
                            label="问题大类"
                            style="width:120px;"
                            dense
                            outlined
                            hide-details
                            @change="onProblemClassChange"
                    ></v-select>
                </div>
            </div>
            <div ref="matrixTarget" style="width:100%;height:45vh"></div>
        </v-card>

        <v-card style="padding-left:10px;padding-right:10px;margin-top:3px;padding-bottom:20px">
            <h3 style="padding-top:3px" >【{{problem_subclass}}】再发防止鱼骨图</h3>
            <v-row class="px-2 d-flex align-end">
                <v-col cols="4" style="padding-right:80px;position:relative" v-for="item in topDataInfo">
                    <div style="border: 2px dashed;border-radius:5px"  :style="{borderColor: item.color}">
                        <div class="d-flex" style="justify-content: right;padding-top: 5px;padding-bottom: 5px" :style="{paddingRight:item.offset + 'px'}">
                            <v-chip
                                    class="font-weight-bold mr-1"
                                    :color="item.color"
                                    label
                            >
                                {{ item.title }}
                            </v-chip>
                        </div>
                        <v-hover v-for="(content,index) in item.content">
                            <template v-slot:default="{ hover }"><v-card :elevation="hover ? 10 : 3" style="margin:3px" @click="go_to_ll(content.linkInfo)"><h4 class="d-flex" style="padding:3px"  >{{(index+1)}}、{{ content.data }}</h4></v-card></template>
                        </v-hover>
                    </div>
                    <v-icon style="position:absolute;bottom:-7px;right:63px;" :color="item.color">
                        mdi-arrow-bottom-right
                    </v-icon>
                </v-col>
            </v-row>
            <v-row class="px-2 d-flex align-center" >
                <v-chip
                        class="font-weight-bold mr-1"
                        style="flex-grow: 1;justify-content: right;padding-right:20px"
                        color="#BBDEFB"
                >
                    {{problem_subclass}}
                </v-chip>
                <v-icon
                        color="#BBDEFB"
                        size="50"
                        x-large
                        style="flex-shrink: 0;margin-left:-30px"
                >
                    mdi-arrow-right-bold
                </v-icon>
            </v-row>
            <v-row class="px-2 d-flex">
                <v-col cols="4" style="padding-right:50px;padding-left:30px;position:relative" v-for="item in bottomDataInfo">
                    <div style="border: 2px dashed;border-radius:5px" :style="{borderColor: item.color}">
                        <v-hover v-for="(content,index) in item.content">
                            <template v-slot:default="{ hover }"><v-card :elevation="hover ? 10 : 3" style="margin:3px" @click="go_to_ll(content.linkInfo)" ><h4 class="d-flex" style="padding:3px"  >{{(index+1)}}、{{ content.data }}</h4></v-card></template>
                        </v-hover>
                        <div class="d-flex" style="justify-content: right;padding-top: 5px;padding-bottom: 5px" >
                            <v-chip
                                    class="font-weight-bold mr-1"
                                    :color="item.color"
                                    label
                            >
                                {{ item.title }}
                            </v-chip>
                        </div>
                    </div>
                    <v-icon style="position:absolute;top:-5px;right:32px;" :color="item.color">
                        mdi-arrow-top-right
                    </v-icon>
                </v-col>
            </v-row>
        </v-card>
    </v-card>
</template>
<script>
    export default {
        data () {
            return {
                fish_bone_sql:"select l.id as long_id,l.measure,l.problem_process_id,process.process_type,l.reason_analyse_id,r.type,r.reason_analyse,r.if_primary,l.lessons_learn_id,ll.problem_subclass from tb_long_term_measure l left join tb_lessons_learn ll on l.lessons_learn_id = ll.id and ll.MARK_FOR_DELETE = 0 left join tb_problem_process process on l.PROBLEM_PROCESS_ID = process.id and process.MARK_FOR_DELETE = 0 left join tb_reason_analyse r on l.REASON_ANALYSE_ID = r.id and r.MARK_FOR_DELETE = 0 where l.MARK_FOR_DELETE = 0 and l.RELATION_LESSONS_LEARN = 'Y' and l.REASON_ANALYSE_ID is not null  [and ll.problem_subclass = #{problem_subclass}]",
                matrix_sql:"select ll.problem_subclass,r.type,count(1) num from tb_long_term_measure l left join tb_lessons_learn ll on l.lessons_learn_id = ll.id and ll.MARK_FOR_DELETE = 0 left join tb_reason_analyse r on l.REASON_ANALYSE_ID = r.id and r.MARK_FOR_DELETE = 0 where l.MARK_FOR_DELETE = 0 and l.RELATION_LESSONS_LEARN = 'Y' and l.REASON_ANALYSE_ID is not null and ll.problem_subclass != '其他（需要备注）' [and ll.problem_class_id = #{problem_class_id}] group by r.type,ll.problem_subclass order by r.type,ll.problem_subclass",
                problem_class_sql:"SELECT problem_class as label,id as value FROM tm_problem_class where MARK_FOR_DELETE = 0",
                problem_subclass:'',
                selectedProblemClass: 'ALL',
                problemClassList: [{value: 'ALL', label: '全部'}],
                topDataInfo:[],
                bottomDataInfo:[],
                matrixXData:['人', '机', '料', '法', '环', '测'],
                matrixYData:[],
                matrix:[],
                matrixEvent:'',
                visualMapMax:2,
                dataZoomEnd:100,
            }
        },
        methods: {
            show(){
                app.utils.showMessage(this.prop);
            },
            go_to_ll(data){
                this.$emit('toPage', 'vbd924c209c45508ce0bc310855', {"problem_process_id":data.problem_process_id,"process_type":data.process_type,"long_id":data.long_id,"reason_analyse_id":data.reason_analyse_id});
            },
            loadProblemClassList() {
                let _this = this;
                let params = {"SQL": this.problem_class_sql};

                app.utils.ajaxRequest({
                    hideMsg: true,
                    hideMask: false,
                    url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
                    params: {
                        functionParam: JSON.stringify(params),
                    },
                    callBack(res) {
                        // 过滤掉"其他"和"设备"选项
                        let filteredRows = res.rows.filter(item =>
                            item.label !== '其他' && item.label !== '设备'
                        );

                        // 添加"全部"选项
                        let allList = [{value: 'ALL', label: '全部'}].concat(filteredRows);
                        _this.problemClassList = allList;
                    },
                });
            },
            onProblemClassChange() {
                this.loadMatrixData();
            },
            generateHeatmapData() {
                // 初始化一个二维数组，全部填充0
                const dataMap = this.matrixYData.map(() => new Array(this.matrixXData.length).fill(0));

                // 填充实际数据
                this.matrix.forEach(item => {
                    const yIndex = this.matrixYData.indexOf(item.problem_subclass);
                    const xIndex = this.matrixXData.indexOf(item.type);
                    if (yIndex !== -1 && xIndex !== -1) {
                        dataMap[yIndex][xIndex] += item.num;
                    }
                });

                // 转换为目标格式，包括所有可能的组合
                const result = [];
                for (let y = 0; y < this.matrixYData.length; y++) {
                    for (let x = 0; x < this.matrixXData.length; x++) {
                        result.push([x, y, dataMap[y][x] || '-']);
                    }
                }

                return result;
            },
            loadMatrixData(){
                let _this = this;
                let params = {"SQL": this.matrix_sql};

                // 设置查询条件
                let queryCondition = {};
                if(this.selectedProblemClass && this.selectedProblemClass !== 'ALL') {
                    queryCondition["problem_class_id"] = this.selectedProblemClass;
                }

                app.utils.ajaxRequest({
                    hideMsg: true,
                    hideMask: false,
                    url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
                    params: {
                        functionParam: JSON.stringify(params),
                        queryCondition: queryCondition
                    },
                    callBack(res) {
                        let subClass = new Set();
                        let max = 2;
                        res.rows.forEach(function (item) {
                            item.type = app.utils.getEntryValue("REASON_ANALYSE_TYPE", item.type);
                            subClass.add(item.problem_subclass);
                            if(item.num > max){
                                max = item.num;
                            }
                        })

                        _this.visualMapMax = max;

                        _this.matrix  = res.rows;

                        // 创建一个包含problem_subclass和总数的数组
                        let subClassWithTotals = [];
                        Array.from(subClass).forEach(cls => {
                            let total = 0;
                            // 计算每个类别在各个原因类型下的总数
                            res.rows.forEach(item => {
                                if (item.problem_subclass === cls) {
                                    total += Number(item.num);
                                }
                            });
                            subClassWithTotals.push({
                                name: cls,
                                total: total
                            });
                        });

                        // 按总数排序，大的在上面（索引小），小的在下面（索引大）
                        subClassWithTotals.sort((a, b) => b.total - a.total);
                        _this.matrixYData = subClassWithTotals.map(item => item.name);

                        if(_this.matrixYData.length > 5){
                            _this.dataZoomEnd = Math.ceil(500/_this.matrixYData.length)
                        }

                        _this.loadMatrixChart();
                        if(_this.matrixYData.length > 0){
                            _this.problem_subclass = _this.matrixYData[0];
                            _this.loadFishBoneData();
                        }
                    },
                })
            },
            loadMatrixChart(){
                this.matrixEvent = this.matrixEvent || this.$echarts.init(this.$refs.matrixTarget);
                const data = this.generateHeatmapData();
                let option = {
                    tooltip: {

                        trigger: 'item',
                        formatter: function(params) {
                            const data = params.data;
                            const xName = option.xAxis.data[data[0]];
                            const yName = option.yAxis.data[data[1]];
                            const value = data[2];

                            // 添加图标
                            const icon = value > 0 ? '●' : '○';

                            return `
      <div style="font-size:14px">
        <div style="font-weight:bold;margin-bottom:5px">
          ${icon} ${yName}
        </div>
        <div style="display:flex">
          <span style="width:80px;color:#888">所属分类：</span>
          <span>${xName}</span>
        </div>
        <div style="display:flex">
          <span style="width:80px;color:#888">出现次数：</span>
          <span style="color:${params.color}">
            ${value === '-' ? '无记录' : value + '次'}
          </span>
        </div>
      </div>
    `;
                        }
                    },
                    grid: {
                        left: '2%',
                        right:'2%',
                        top: '2%',
                        bottom:'3%',
                        containLabel:true
                    },
                    xAxis: {
                        type: 'category',
                        position:'top',
                        data: this.matrixXData,
                        splitArea: {
                            show: true
                        },
                        axisLabel: {
                            color: '#66BB6A',
                            fontWeight: 'bold'
                        }
                    },
                    yAxis: {
                        type: 'category',
                        data: this.matrixYData,
                        splitArea: {
                            show: true
                        },
                        inverse: true,  // 反转Y轴，确保最大值在最上面
                        axisLabel: {
                            color: '#42A5F5',
                            fontWeight: 'bold'
                        }
                    },
                    dataZoom: [
                        {
                            yAxisIndex:0,
                            left:'0.5%',
                            show: true,
                            realtime: true,
                            start: 0,
                            end: this.dataZoomEnd
                        }
                    ],
                    visualMap: {
                        show: false,
                        min: 1,
                        max: this.visualMapMax,
                        color:['#66BB6A','#66BB6A']
                    },
                    series: [
                        {
                            name: '矩阵图',
                            type: 'heatmap',
                            data: data,
                            label: {
                                show: true
                            },
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                }
                let _this = this;
                option && this.matrixEvent.setOption(option);
                this.matrixEvent.off('click');
                this.matrixEvent.on('click', function (params) {
                    _this.problem_subclass = _this.matrixYData[params.data[1]];
                    _this.loadFishBoneData();
                });
            },
            loadFishBoneData(){
                let _this = this;
                let params = {"SQL": this.fish_bone_sql};

                app.utils.ajaxRequest({
                    hideMsg: true,
                    hideMask: false,
                    url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
                    params: {
                        functionParam: JSON.stringify(params),
                        "queryCondition[problem_subclass]": _this.problem_subclass,
                    },
                    callBack(res) {
                        res.rows.forEach(function (item) {
                            item.type = app.utils.getEntryValue("REASON_ANALYSE_TYPE", item.type);
                        })
                        _this.transformData(res.rows);
                    },
                })
            },
            transformData(originalData) {
                // Define the categories and their properties
                const topCategories = [
                    { type: '人', title: '【人】', color: '#74b567' },
                    { type: '机', title: '【机】', color: '#26C6DA' },
                    { type: '料', title: '【料】', color: '#459ce3' }
                ];

                const bottomCategories = [
                    { type: '法', title: '【法】', color: '#f8b500' },
                    { type: '环', title: '【环】', color: '#8e81bc' },
                    { type: '测', title: '【测】', color: '#7dcdf4' }
                ];

                // Initialize the result objects
                const topDataInfo = topCategories.map(cat => ({
                    title: cat.title,
                    color: cat.color,
                    offset: 0,
                    content: []
                }));

                const bottomDataInfo = bottomCategories.map(cat => ({
                    title: cat.title,
                    color: cat.color,
                    offset: 0,
                    content: []
                }));

                // Process each item in the original data
                originalData.forEach(item => {
                    const contentItem = {
                        linkInfo: item,
                        //data: item.reason_analyse,  //原因分析
                        data: item.measure, //长期措施
                        offset: 0
                    };

                    // Check if the item belongs to top categories
                    const topCategory = topCategories.find(cat => cat.type === item.type);
                    if (topCategory) {
                        const target = topDataInfo.find(info => info.title === topCategory.title);
                        if (target) {
                            target.content.push(contentItem);
                        }
                    }

                    // Check if the item belongs to bottom categories
                    const bottomCategory = bottomCategories.find(cat => cat.type === item.type);
                    if (bottomCategory) {
                        const target = bottomDataInfo.find(info => info.title === bottomCategory.title);
                        if (target) {
                            target.content.push(contentItem);
                        }
                    }
                });

                this.topDataInfo  = topDataInfo;
                this.bottomDataInfo = bottomDataInfo;
            }
        },
        mounted () {
            this.loadProblemClassList();
            this.loadMatrixData();
            window.onresize=()=>{
                this.matrixEvent.resize();
            }
        },
        props: {
            prop:{type:String,desc:'基本参数'}
        }
    }
</script>
